<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>卡码五子棋</title>
    <style>
        /* 全局样式 */
        body {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "Microsoft YaHei", Arial, sans-serif;
            background-color: #1e1e2f;
            color: #fff;
            overflow: hidden;
        }

        /* 加载动画容器 */
        #loading-container {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            text-align: center;
        }

        /* 加载标题 */
        #loading-title {
            font-size: 2em;
            margin-bottom: 20px;
            color: #00c3ff;
            text-shadow: 0 0 5px #00c3ff, 0 0 10px #008bff;
        }

        /* 进度条 */
        .progress-bar {
            width: 300px;
            height: 20px;
            background: #444;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 0 10px #000;
        }

        .progress-bar-inner {
            height: 100%;
            background: linear-gradient(to right, #00c3ff, #00e1ff);
            width: 0;
            transition: width 1.5s ease;
        }

        /* 加载提示文字 */
        #loading-text {
            margin-top: 15px;
            font-size: 1.2em;
            color: #ccc;
        }

        /* 菜单页面样式 */
        #menu-container {
            display: none;
            text-align: center;
            padding: 50px 20px;
        }

        h1 {
            font-size: 2.5em;
            margin-bottom: 30px;
            color: #00c3ff;
            text-shadow: 0 0 5px #00c3ff, 0 0 10px #008bff;
        }

        .menu-option {
            margin: 10px 0;
            font-size: 1.5em;
            color: #fff;
            cursor: pointer;
            transition: color 0.3s ease;
        }

        .menu-option:hover {
            color: #00e1ff;
            text-shadow: 0 0 5px #00e1ff;
        }

        .menu-border {
            margin: 10px auto;
            width: 80%;
            height: 2px;
            background: #00c3ff;
            box-shadow: 0 0 5px #00c3ff;
        }

        /* 输入提示样式 */
        #input-hint {
            font-size: 1.2em;
            margin-top: 20px;
            color: #00e1ff;
        }

        input {
            margin-top: 10px;
            font-size: 1em;
            padding: 5px 10px;
            border-radius: 5px;
            border: none;
            outline: none;
            text-align: center;
            background-color: #333;
            color: #fff;
        }
    </style>
</head>

<body>
    <!-- 加载动画 -->
    <div id="loading-container">
        <div id="loading-title">卡码五子棋</div>
        <div class="progress-bar">
            <div class="progress-bar-inner"></div>
        </div>
        <div id="loading-text">加载中...</div>
    </div>

    <!-- 菜单页面 -->
    <div id="menu-container">
        <h1>欢迎来到卡码五子棋</h1>
        <div class="menu-border"></div>
        <div class="menu-option" id="play-ai">[1] 对战AI</div>
        <div class="menu-option">[2] 匹配玩家</div>
        <div class="menu-option">[0] 退出游戏</div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Page loaded'); // 调试日志
            
            const progressBar = document.querySelector('.progress-bar-inner');
            const loadingContainer = document.getElementById('loading-container');
            const menuContainer = document.getElementById('menu-container');

            if (!progressBar || !loadingContainer || !menuContainer) {
                console.error('Required elements not found');
                return;
            }

            // 强制触发重排以确保动画生效
            void progressBar.offsetWidth;
            
            // 设置进度条
            progressBar.style.width = '100%';

            // 监听过渡结束事件
            progressBar.addEventListener('transitionend', function() {
                console.log('Progress bar animation completed');
                loadingContainer.style.display = 'none';
                menuContainer.style.display = 'block';
            });

            // 添加超时保护
            setTimeout(() => {
                if (loadingContainer.style.display !== 'none') {
                    console.log('Timeout triggered - forcing menu display');
                    loadingContainer.style.display = 'none';
                    menuContainer.style.display = 'block';
                }
            }, 2000); // 2秒后强制显示菜单
        });

        // 对战AI功能
        function startAiGame() {
            const userId = sessionStorage.getItem('userId');
            
            fetch('/aiBot/start', {
                method: 'GET',
                headers: {
                    'Accept': 'text/html'
                }
            })
            .then(response => response.text())
            .then(html => {
                // 完全清除当前页面
                document.open();
                document.write(html);
                document.close();
                
                // 确保在页面完全加载后初始化
                if (document.readyState === 'loading') {
                    document.addEventListener('DOMContentLoaded', function() {
                        if (typeof initializeGame === 'function') {
                            initializeGame();
                        }
                    });
                } else {
                    if (typeof initializeGame === 'function') {
                        initializeGame();
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('启动AI对战失败，请稍后重试！');
            });
        }

        // 绑定点击事件到对战AI按钮
        document.getElementById('play-ai').addEventListener('click', startAiGame);

        // 添加页面刷新/关闭时的处理
        window.addEventListener('beforeunload', function(e) {
            const userId = sessionStorage.getItem('userId');
            if (userId) {
                try {
                    // 创建 Blob 对象，指定 content-type
                    const data = new Blob([JSON.stringify({
                        userId: userId,
                        type: 'refresh',
                        gameType: 0
                    })], { type: 'application/json' });

                    // 使用 navigator.sendBeacon 发送异步请求
                    const success = navigator.sendBeacon('/user/logout', data);
                    
                    // 如果 sendBeacon 失败，尝试使用同步 XMLHttpRequest
                    if (!success) {
                        const xhr = new XMLHttpRequest();
                        xhr.open('POST', '/user/logout', false); // 同步请求
                        xhr.setRequestHeader('Content-Type', 'application/json');
                        xhr.send(JSON.stringify({
                            userId: userId,
                            type: 'refresh',
                            gameType: 0
                        }));
                    }
                } catch (error) {
                    console.error('Logout error:', error);
                }
            }
        });

        // 添加页面加载时的用户检查
        window.addEventListener('load', function() {
            const userId = sessionStorage.getItem('userId');
            if (!userId) {
                window.location.href = '/entry';
                return;
            }
        });
    </script>
</body>

</html>